package qf.index;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

public class ChinaHosp {

    public static void main(String[] args) throws SQLException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(new Date()) + " 程序开始了~~~");
        String tbTrueTable = "scholar_25_01.tb_true_china_hosp_6_year";
        String utArticleTable = "scholar_25_01.spider_tb_true_92007022_1125";
        String chinaHospTable = "scholar_25_01.wos_china_hosp_6_year";
        String deptTable = "scholar_25_01.wos_china_hosp_6_year_dept";
        String hospTable = "scholar_25_01.wos_china_hosp_6_year_hosp";
        String basicDeptTable = "scholar_25_01.tb_true_china_hosp_6_year_dept";
        String basicHospTable = "scholar_25_01.tb_true_china_hosp_6_year_hosp";
        String basicCoreTable = "scholar_25_01.basic_core_paper";
        String cnBasicDeptTable = "scholar_25_01.cn_dept_sum_dy30";
        String basicUnivCollTable = "scholar_25_01.basic_univ_coll";
        String htLocationChinaTable = "scholar_25_01.ht_location_china";
        String basicHospUnivDeptTable = "scholar_25_01.basic_hosp_or_univ_dept";


        // 本表是在原来的已经过滤出中国人，且包含医院的表中来的，如果直接使用
//        updateUnitDeptAuth(utArticleTable, "pid", "UT`,`C1`,`RP`,`PY", deptTable, hospTable, basicHospTable, basicDeptTable, chinaHospTable, basicCoreTable, cnBasicDeptTable, basicUnivCollTable, htLocationChinaTable);

    }

    /**
     * update wos_china_hosp_6_year AS a join basic_core_paper_citation AS b ON a.pid = b.pid SET a.citation = b.citation_id, a.citation_sum = b.citation_total;
     * update wos_china_hosp_6_year AS a join basic_core_paper_reference AS b ON a.pid = b.pid SET a.reference = b.reference_id, a.reference_sum = b.reference_total;
     */

//    public static void updateUnitDeptAuth(String utArticleTable, String autoId, String field, String deptTable, String hospTable, String basicHospTable, String enBasicDeptTable, String chinaHospTable, String basicCoreTable, String cnBasicDeptTable, String basicUnivCollTable, String htLocationChinaTable) throws SQLException {
//        // 将原始的C1和RP转换为实体类，并将dept和hosp加入翻译列表，供人工加AI翻译后使用。basicHospTable和basicDeptTable是之前翻译的，供本次使用。deptTable和hospTable是本次新产生的，需要人工加AI翻译后再使用。
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Db.use().execute("truncate table " + chinaHospTable);
//        Set<String> stemSet = uSet.getStemSet();
//        Set<String> fuDanSet = uSet.getFuDanSet();
//        Set<String> chinaSet = cList.chinaSet();
//        Map<String, List<String>> deptAndFuDanOrStemListMap = new HashMap<>();
//        Guidelines.getEnDeptAndFuDanOrStemListMap(enBasicDeptTable, "id", "info`,`fudan`,`stem", stemSet, fuDanSet, deptAndFuDanOrStemListMap);
//        Guidelines.getCnDeptAndFuDanOrStemListMap(cnBasicDeptTable, "id", "info`,`fudan`,`stem", stemSet, fuDanSet, deptAndFuDanOrStemListMap);
//        deptAndFuDanOrStemListMap = Guidelines.mapSortValueStrLen(deptAndFuDanOrStemListMap);
////        Map<String, List<String>> deptAndFuDanOrStemListMap = Guidelines.getEnDeptAndFuDanOrStemListMap(basicDeptTable, "id", "info`,`fudan`,`stem", stemSet, fuDanSet);
////        Map<String, List<String>> cnDeptAndFuDanOrStemListMap = Guidelines.getCnDeptAndFuDanOrStemListMap(cnBasicDeptTable, "id", "info`,`fudan`,`stem", stemSet, fuDanSet);
//        System.out.println(format.format(new Date()) + " deptAndFuDanOrStemListMap.size()：" + deptAndFuDanOrStemListMap.size());
//        Map<List<String>, String> infoAndUnitMap = Guidelines.getInfoAndUnitMap(basicHospTable, "id", "info`,`standard");
//        System.out.println(format.format(new Date()) + " infoAndUnitMap.size()：" + infoAndUnitMap.size());
//        Map<String, Integer> utAndPidMap = getUtAndPidMap(basicCoreTable, "id", "wos_ut");
//        System.out.println(format.format(new Date()) + " utAndPidMap.size()：" + utAndPidMap.size());
//        int onePageNum = 10000;
//        List<Entity> tableNum = Db.use().query("select count(1) as count from " + utArticleTable);
//        Map<String, String> standardMap = new ConcurrentHashMap<>();
//        standardMap.put("department medical", "Department Medical");
//        Map<Set<String>, Set<String>> unitAndSumMap = new ConcurrentHashMap<>();
//        Map<String, Set<String>> deptAndInfoSetMap = new ConcurrentHashMap<>();
//        Map<String, Integer> deptAndSumMap = new ConcurrentHashMap<>();
//        Map<String, String> countryMap = cList.getCountryMap();
//        Set<String> acadSet = uSet.getAcadSet();
//        Set<String> centerSet = uSet.getCenterSet();
//        Set<String> collSet = uSet.getCollSet();
//        Set<String> hospSet = uSet.getHospSet();
//        Set<String> univSet = uSet.getUnivSet();
//        Set<String> removeSet = uSet.getRemoveSet();
//        Set<String> deptSet = uSet.getDeptSet();
//        Set<String> dellSet = uSet.getDellSet();
//        Set<String> nameSet = cList.getProvName();
//        Set<String> notCollSet = cList.getNotCollSet();
//        Set<String> citySet = new HashSet<>();
//        Set<String> subjectSet = cList.getSubjectSet();
//        Set<String> provCitySet = Dept.getProvCitySet(htLocationChinaTable, "id", "prov`,`name", citySet);
//        Map<String, En.Edu> collAndEduMap = Guidelines.getCollAndEduMap(basicUnivCollTable, "id", "info`,`edu", notCollSet);
//        Map<String, List<String>> finalDeptAndFuDanOrStemListMap = deptAndFuDanOrStemListMap;
//        if (tableNum.get(0).getInt("count") > 0) {
//            int tableMax = Db.use().queryNumber("select max(" + autoId + ") from " + utArticleTable).intValue();
//            Collection<Integer> tableList = new ArrayList<>();
//            NumberUtil.appendRange(0, tableMax + onePageNum, onePageNum, tableList);
//
//            tableList.parallelStream().forEach(startId -> {
//                try {
//                    List<Entity> tableData = Db.use().query("select `" + autoId + "`,`" + field + "` from " + utArticleTable + " where " + autoId + " between " + startId + " and " + (startId + onePageNum - 1));
//                    System.out.println("\033[31;1m" + format.format(new Date()) + " 读表现在开始：" + startId + " 表名：" + utArticleTable + Utils.printMemoryStr() + "\033[0m");
//                    for (Entity entry : tableData) {
//                        int id = Utils.getIntField(entry, autoId);
//                        String ut = Utils.getStrField(entry, "UT");
//                        String c1 = Utils.getStrField(entry, "C1");
//                        String rp = Utils.getStrField(entry, "RP");
//                        String py = Utils.getStrField(entry, "PY");
//                        ut = ut.toUpperCase().replace(" ", "").replace("WOS:", "").trim();
//                        if (("2019".equals(py) || "2020".equals(py) || "2021".equals(py) || "2022".equals(py) || "2023".equals(py) || "2024".equals(py) || "2025".equals(py)) && (c1.length() > 3 || rp.length() > 3) && id > 0 && ut.length() == 15 && utAndPidMap.containsKey(ut)) {
//                            List<En.C1Auth> c1List = Utils.getC1List(c1);
//                            List<En.C1Auth> rpList = Utils.getRpList(rp);
//                            List<En.C1Auth> rpChangeC1 = ChangeRp.rpChangeC1(c1List, rpList);
//                            if (isChinaHosp(c1List, nameSet, hospSet, removeSet) || isChinaHosp(rpChangeC1, nameSet, hospSet, removeSet)) {
////                                Guidelines.setC1List(c1List, standardMap, acadSet, centerSet, collSet, hospSet, univSet, removeSet, countryMap, unitAndSumMap, finalDeptAndFuDanOrStemListMap, deptAndSumMap,  dellSet, fuDanSet, stemSet,  chinaSet, collAndEduMap, provCitySet, citySet, subjectSet,deptAndInfoSetMap);
////                                Guidelines.setC1List(rpChangeC1, standardMap, acadSet, centerSet, collSet, hospSet, univSet, removeSet, countryMap, unitAndSumMap, finalDeptAndFuDanOrStemListMap, deptAndSumMap,  dellSet, fuDanSet, stemSet,  chinaSet, collAndEduMap, provCitySet, citySet, subjectSet,deptAndInfoSetMap);
//                                try {
//                                    Db.use().insert(Entity.create(chinaHospTable).set("ut", ut).set("pid", utAndPidMap.get(ut)).set("C1", c1).set("RP", rp).set("py", Integer.parseInt(py))
//                                            .set("c1_list", JSONUtil.toJsonStr(c1List)).set("rp_list", JSONUtil.toJsonStr(rpList)).set("change_rp", JSONUtil.toJsonStr(rpChangeC1)));
//                                } catch (SQLException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        }
//                    }
//                } catch (SQLException e) {
////                    throw new RuntimeException(e);
//                }
//            });
//        }

    /// /        Db.use().execute("truncate table " + hospTable);
    /// /        unitAndSumMap.keySet().parallelStream().forEach(unitSet -> {
    /// /            Set<String> set = unitAndSumMap.get(unitSet);
    /// /            List<String> infoList = JSONObject.parseArray(JSONUtil.toJsonStr(unitSet).toLowerCase(), String.class);
    /// /            Collections.sort(infoList);
    /// /            String standard = infoAndUnitMap.getOrDefault(infoList, "");
    /// /            try {
    /// /                Db.use().insert(Entity.create(hospTable).set("info", JSONUtil.toJsonStr(unitSet)).set("c1s", JSONUtil.toJsonStr(set)).set("sum", set.size()).set("standard", standard));
    /// /            } catch (SQLException e) {
    /// /                e.printStackTrace();
    /// /            }
    /// /        });
    /// /        Db.use().execute("truncate table " + deptTable);
    /// /        deptAndSumMap.keySet().parallelStream().forEach(dept -> {
    /// /            Set<String> set = deptAndSumMap.get(dept);
    /// /            String fuDan = "";
    /// /            String stem = "";
    /// /            String trim = dept.toLowerCase().trim();
    /// /            if (finalDeptAndFuDanOrStemListMap.containsKey(trim)) {
    /// /                List<String> list = finalDeptAndFuDanOrStemListMap.get(trim);
    /// /                if (null != list && list.size() == 2) {
    /// /                    fuDan = list.get(0);
    /// /                    stem = list.get(1);
    /// /                }
    /// /            }
    /// /            try {
    /// /                Db.use().insert(Entity.create(deptTable).set("info", dept).set("c1s", JSONUtil.toJsonStr(set)).set("sum", set.size()).set("fudan", fuDan).set("stem", stem));
    /// /            } catch (SQLException e) {
    /// /                e.printStackTrace();
    /// /            }
    /// /        });
//    }


//    public static Map<String, Integer> getUtAndPidMap(String basicCoreTable, String autoId, String field) throws SQLException {
//        int onePageNum = 1000;
//        List<Entity> tableNum = Db.use().query("select count(1) as count from " + basicCoreTable);
//        Map<String, Integer> utAndPidMap = new HashMap<>();
//        if (tableNum.get(0).getInt("count") > 0) {
//            int tableMax = Db.use().queryNumber("select max(" + autoId + ") from " + basicCoreTable).intValue();
//            Collection<Integer> tableList = new ArrayList<>();
//            NumberUtil.appendRange(0, tableMax + onePageNum, onePageNum, tableList);
//            for (Integer startId : tableList) {
//                List<Entity> tableData = Db.use().query("select `" + autoId + "`,`" + field + "` from " + basicCoreTable + " where " + autoId + " between " + startId + " and " + (startId + onePageNum - 1));
//                for (Entity entry : tableData) {
//                    String uts = entry.getStr("wos_ut");
//                    Integer id = entry.getInt(autoId);
//                    if (null != uts && uts.length() > 14 && null != id && id > 0) {
//                        String[] split = uts.replace(" ", "").split(",");
//                        for (String ut : split) {
//                            ut = ut.toUpperCase().replace(" ", "").replace("WOS:", "").trim();
//                            utAndPidMap.put(ut, id);
//                        }
//                    }
//                }
//            }
//        }
//        return utAndPidMap;
//    }
    public static boolean isChinaHosp(List<En.C1Auth> c1List, Set<String> nameSet, Set<String> hospSet, Set<String> removeSet) {
        if (null == c1List || c1List.isEmpty()) {
            return false;
        }
        for (En.C1Auth c1Auth : c1List) {
            if (c1IsChinaHosp(c1Auth.getInfo().toLowerCase().trim(), nameSet, hospSet, removeSet)) {
                return true;
            }
        }
        return false;
    }

    public static boolean c1IsChinaHosp(String c1, Set<String> nameSet, Set<String> hospSet, Set<String> removeSet) {
//        String c1 = c1Auth.getInfo().toLowerCase().trim();
        String[] split = c1.replace(": ", ", ").replace(";", ", ").replace(". ", ", ").split(",");
        boolean isChina = c1.contains("pr china") || c1.contains("peoples r china") || c1.contains("republic of china") || c1.contains("p. r. china") || c1.contains("people's republic of china") ||
                c1.contains("petrochina") || c1.contains("westchina") || c1.contains("chinamed") || c1.contains("immunochina") || c1.contains("chinajapan") || c1.contains("powerchina") ||
                c1.contains("southchina") || c1.contains("eastchina") || c1.contains("chinathree") || c1.contains("china570311") || c1.contains("china450000") || c1.contains("china733000");
        for (String s : split) {
            s = s.replaceAll(" +", " ").trim();
            if (!isChina) {
                for (String n : nameSet) {
                    if (n.equals(s) || s.contains(" " + n + " ") || s.startsWith(n + " ") || s.endsWith(" " + n)) {
                        isChina = true;
                        break;
                    }
                }
            }
            if (isChina) {
                if (Unit.isHosp(s, hospSet, removeSet)) {
                    return true;
                }
            }
        }
        return false;
    }


}
